<?php

namespace app\index\controller;

use app\api\controller\Complain;
use think\Db;
use think\Cookie;
use addons\workorder\model\Kbs;
use addons\workorder\model\Orders;
use app\common\controller\Frontend;
use addons\workorder\model\Engineer;
use app\admin\model\workorder\Fields;
use addons\workorder\library\General;

class Workorder extends Frontend
{
    protected $noNeedRight = ['*'];
    protected $layout      = 'default';
    protected $fileField   = ['image', 'images', 'file', 'files'];

    /**
     * @var General 实例
     */
    protected $General = null;

    protected $userEngineerId  = null;
    protected $workorderConfig = [];

    public function _initialize()
    {
        parent::_initialize();

        $this->General = General::instance();

        // 当前用户是否是工程师
        if ($this->auth) {
            $this->userEngineerId = Engineer::where('user_id', $this->auth->id)->where('status', '1')->value('id');
        }

        $this->workorderConfig = get_addon_config('workorder');

        $this->General->autoClose();
    }

    public function my()
    {
        $page = $this->request->param('page');
        if ($this->request->isDelete()) {
            $order_id = (int)$this->request->param('order_id');
            $order    = Orders::get($order_id);
            if ($order->status != 5) {
                $this->error(__('You can delete a work order after closing it!'));
            }
            if (Orders::destroy(['id' => $order_id, 'user_id' => $this->auth->id])) {
                General::orderNumberChangeCalcEngineerStatistics($order->id, $order->engineer_id);
                $this->success(__('Delete Success~'));
            } else {
                $this->error(__('Delete Fail!'));
            }
        }

        $orders = Orders::where('user_id', $this->auth->id)
            ->order('createtime desc')
            ->paginate(10, null)
            ->each(function ($item) {
                $item->status = $this->General->handleStatus($item->status, false);
                $item->title  = $item->title ?? __('Untitled');
            });

        // 防止删除后当页显示空白
        if (count($orders) == 0 && $page > 1) {
            $this->redirect('workorder/my');
        }

        $this->view->assign('title', __('My work order'));
        $this->view->assign('orders', $orders);
        return $this->view->fetch();
    }

    public function manage()
    {
        if (!$this->userEngineerId) {
            $this->error(__('You have no permission to operate!'));
        }
        $page = $this->request->param('page');
        $type = $this->request->param('type') ?? 'all';

        $where['engineer_id'] = $this->userEngineerId;
        switch ($type) {
            case 'noreply':
                $where['status'] = ['in', '1,2'];
                break;
            case 'replied' :
                $where['status'] = 3;
                break;
            case 'closed':
                $where['status'] = ['in', '4,5'];
                break;
        }

        $orders = Orders::where($where)
            ->order('createtime desc')
            ->paginate(10, null)
            ->each(function ($item) {
                $item->title  = $item->title ?? __('Untitled');
                $item->status = $this->General->handleStatus($item->status, true);
            });

        if (count($orders) == 0 && $page > 1) {
            $this->redirect('workorder/manage');
        }

        $this->view->assign('title', __('work order manage'));
        $this->view->assign('orders', $orders);
        $this->view->assign('type', $type);
        return $this->view->fetch();
    }

    public function reply($id)
    {
        $token = $this->request->post('__token__');
        if (session('__token__') != $token) {
            $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
        }

        $order = Orders::get($id);
        if (!$order) {
            $this->error(__('Work order not found~'));
        }

        $user     = ($order->user_id == $this->auth->id) ? $this->auth : false;
        $engineer = ($order->engineer_id == $this->userEngineerId) ? Engineer::get($this->userEngineerId) : false;
        if (!$user && !$engineer) {
            $this->error(__('You have no permission to operate!'), null, ['token' => $this->request->token()]);
        }

        $row = $this->request->post('row/a');
        print_r($row);exit;
        $attachment   = explode(',', trim($row['reply_attachment'], ','));
        if(count($attachment) > 4) {
            $this->error(__('不能超过四张图片'), null, ['token' => $this->request->token()]);
        }
        
        $res = $this->General->createReply($order, $user, $engineer, $row);
        $this->assignconfig('editor_name', $this->getEditorName());

        if ($res['code'] == 1) {

            $this->view->engine->layout(false);
            foreach ($res['data']['records'] as $index => $record) {
                $recordsHtml[$index] = $this->view->fetch('workorder/common/message_item', [
                    'record' => $record,
                    'isUser' => (bool)$user
                ]);
            }

            $this->success($res['msg'], '', ['recordsHtml' => $recordsHtml ?? []]);
        } else {
            $this->error($res['msg'], null, ['token' => $this->request->token()]);
        }
    }

    public function transfer($id)
    {
        $row = Orders::get($id);
        if (!$row) {
            $this->error(__('Work order not found~'));
        }
        $isCurrentEngineer = $row->engineer_id === $this->userEngineerId;
        if (!$isCurrentEngineer) {
            $this->error(__('You have no permission to operate!'));
        }

        if ($this->request->isPost()) {
            $token = $this->request->post('__token__');
            if (session('__token__') != $token) {
                $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
            }
            $transferEngineer = $this->request->post('transfer_engineer');

            $res = $this->General->transfer($row, $transferEngineer);
            if ($res['code'] == 1) {
                $this->success($res['msg'], url('index/workorder/manage'));
            } else {
                $this->error($res['msg'], null, ['token' => $this->request->token()]);
            }
        }

        $this->error(__('Nothing happened~'), null, ['token' => $this->request->token()]);
    }

    public function detail($id)
    {
        $row = Orders::get($id);
        if (!$row) {
            $this->error(__('Work order not found~'), url('index/workorder/my'));
        }

        $isUser            = $row->user_id == $this->auth->id;
        $isCurrentEngineer = $row->engineer_id === $this->userEngineerId;
        if (!$isUser && !$isCurrentEngineer) {
            $this->error(__('You have no permission to operate!'));
        }

        if ($this->request->isPost()) {
            $type = $this->request->param('type');
            if ($type == 'close') {
                $this->output($this->General->closeOrder($row, $isCurrentEngineer));
            } elseif ($type == 'urging' && $isUser) {
                $this->output($this->General->urgingOrder($row));
            }
            $this->error(__('Nothing happened~'));
        }

        $orderInfo = $this->General->orderInfoHandle($row, $isUser, $isCurrentEngineer);

        // 聊天记录和工程师资料
        $records = $this->General->orderRecords($id, $row->engineer_id);

        $editorName = $this->getEditorName();
        $replyField = $row->getFields(null, $isUser ? 1 : 2);

        $this->view->assign('row', $orderInfo['order']);
        $this->view->assign('isUser', $isUser);
        $this->view->assign('fields', $replyField);
        $this->view->assign('records', $records['records']);
        $this->view->assign('engineers', $records['engineers']);
        $this->view->assign('title', $orderInfo['order']->title . ' – ' . __('Work order details'));
        $this->view->assign('basicField', $orderInfo['basicField']);
        $this->view->assign('editor_name', $editorName);
        $this->assignconfig('editor_name', $editorName);
        return $this->view->fetch();
    }

    protected function getEditorName()
    {
        $editor     = ['nkeditor', 'umeditor', 'markdown', 'tinymce', 'simditor', 'ueditor', 'summernote'];
        $editorList = get_addon_list();
        foreach ($editor as $item) {
            if (array_key_exists($item, $editorList) && $editorList[$item]['state'] == 1) {
                return $item;
            }
        }
        return 'none';
    }

    /**
     * 输出方法返回结果
     */
    protected function output($res)
    {
        if ($res['code'] == 1) {
            $this->success($res['msg']);
        } else {
            $this->error($res['msg']);
        }
    }

    public function evaluate($id)
    {
        $order = Orders::get($id);
        if (!$order) {
            $this->error(__('Work order not found~'));
        }
        if ($order->status == 1) {
            $this->error(__('The current status of the work order cannot be evaluated~'));
        }
        if ($order->status == 5) {
            $this->error(__('The work order has been evaluated~'));
        }

        if ($this->request->isPost()) {
            $token = $this->request->post('__token__');
            if (session('__token__') != $token) {
                $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
            }

            $row = $this->request->post('row/a');
            $res = $this->General->createEvaluate($order, $row, $this->auth->id);

            if ($res['code'] == 1) {
                $this->success($res['msg'], url('index/workorder/my'));
            } else {
                $this->error($res['msg'], null, ['token' => $this->request->token()]);
            }
        }

        $this->view->assign('title', __('Evaluation Work Order'));
        $this->view->assign('row', $order);
        return $this->view->fetch();
    }

    public function create()
    {
        $keywords = $this->request->param('keywords');
        $category = $this->request->param('category');
        $steps    = $this->request->param('steps');

        // 第一步-选择产品/服务
        if (!$category) {
            $where['status']     = '1';
            $where['deletetime'] = null;
            if ($keywords) {
                $where['pid']  = ['>', 0];
                $where['name'] = ['like', '%' . $keywords . '%'];
            }
            $category_temp = Db::name('workorder_category')->where($where)->order('weigh desc')->select();
            foreach ($category_temp as $key => $item) {
                $category_temp[$key]['logo_image'] = cdnurl($item['logo_image'], true);
            }

            if ($keywords) {
                $category_list[] = [
                    'name'  => __('Query results'),
                    'child' => $category_temp
                ];
            } else {
                foreach ($category_temp as $item) {
                    $pid = $item['pid'];
                    if ($pid == 0) {
                        $category_list[] = $item;
                    } else {
                        $category_child_temp[$pid][] = $item;
                    }
                }
                foreach ($category_list as $index => $item) {
                    $category_list[$index]['child'] = $category_child_temp[$item['id']] ?? [];
                }
            }

            $steps = 1;
            $this->view->assign('title', __('Submit work order'));
            $this->view->assign('category_list', $category_list);
        }

        // 第二步-推荐解决方案
        if ($category && ($steps != 3 || $keywords)) {
            $kbs_ids = Db::name('workorder_category')
                ->where('id', $category)
                ->where('status', '1')
                ->where('deletetime', null)
                ->value('kbs_ids');

            $kbs = [];
            if ($kbs_ids) {
                $where['id']         = ['in', $kbs_ids];
                $where['status']     = '1';
                $where['deletetime'] = null;
                if ($keywords) {
                    $where['title'] = ['like', '%' . $keywords . '%'];
                }

                $kbs = Db::name('workorder_kbs')
                    ->field('id,title,views,likes,url')
                    ->where($where)
                    ->order('weigh desc')
                    ->limit(20)
                    ->select();
            }

            $submit_channel = Db::name('workorder_submit_channel')->where('status', 1)->order('weigh desc')->select();
            foreach ($submit_channel as $index => $item) {
                $submit_channel[$index]['logo_image'] = cdnurl($item['logo_image'], true);
                $submit_channel[$index]['url']        = $this->General->handleUrl($item['url'], $category);
            }

            $steps = 2;
            $this->view->assign('kbs', $kbs);
            $this->view->assign('kbs_count', count($kbs));
            $this->view->assign('title', __('Recommended solutions'));
            $this->view->assign('submit_channel', $submit_channel);
            $this->view->assign('search_kbs', (bool)$keywords);
        }

        // 第三步-创建工单
        if ($category && $steps == 3) {

            $autofillFieldNames = Fields::where([
                'position' => 0,
                'autofill' => 1,
                'status'   => '1',
            ])->column('name');

            // 获取工单的自动填充资料
            $last_workorder = Db::name('workorder_orders')
                ->field($autofillFieldNames)
                ->where('user_id', $this->auth->id)
                ->where('deletetime', null)
                ->order('createtime', 'desc')
                ->find();

            $fields        = Orders::getFields($last_workorder, 0);
            $category_name = Db::name('workorder_category')
                ->where('id', $category)
                ->where('status', '1')
                ->where('deletetime', null)
                ->value('name');

            if (!$category_name) {
                $this->error(__('Product / service classification not found~'));
            }

            if ($this->request->isPost()) {
                $token = $this->request->post('__token__');
                if (session('__token__') != $token) {
                    $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
                }

                $row                = $this->request->post('row/a');
                $row['category_id'] = $category;

                $res = $this->General->createOrder($row, $this->auth->id);
                if ($res['code'] == 1) {
                    $this->success(__('Submitted successfully~'), url('index/workorder/detail', ['id' => $res['data']['id']]));
                } else {
                    $this->error($res['msg'], null, ['token' => $this->request->token()]);
                }
            }

            $urgentrank = Db::name('workorder_urgentrank')
                ->where('status', '1')
                ->where('deletetime', null)
                ->order('weigh desc')
                ->select();
            if (!$urgentrank) {
                $this->error(__('Emergency level of no work order available!'));
            }

            $this->view->assign('fields', $fields);
            $this->view->assign('urgentrank', $urgentrank);
            $this->view->assign('title', __('Create work order'));
            $this->view->assign('category_name', $category_name);
        }

        $this->view->assign('category', $category);
        $this->view->assign('steps', $steps ?? 1);
        return $this->view->fetch();
    }

    public function kbs()
    {
        $id       = $this->request->param('id');
        $category = $this->request->param('category');
        $kbs      = Kbs::get(['id' => $id, 'status' => '1']);
        if (!$kbs) {
            $this->error(__('I cant find the knowledge~'), url('index/workorder/create'));
        }

        if ($this->request->isPost()) {
            $type = $this->request->param('type');
            if ($type == 'likes' || $type == 'dislikes') {
                $cookieName         = 'workorder_kbs_' . $type . '_cookie';
                $workorderKbsCookie = Cookie::get($cookieName);
                if ($workorderKbsCookie) {
                    $workorderKbsCookieArr = explode('|', $workorderKbsCookie);
                    if (in_array($id, $workorderKbsCookieArr)) {
                        $this->error(__('You have already ordered %s!', [($type == 'likes' ? __('fabulous') : __('step on'))]));
                    }
                }
                Db::name('workorder_kbs')->where('id', $id)->setInc($type);
                $workorderKbsCookie .= $id . '|';
                Cookie::set($cookieName, $workorderKbsCookie, 315360000);
                $this->success();
            }
        }

        $kbs->setInc('views');
        $recKbs = $this->General->recKbs($id, $category);

        $this->view->assign('kbs', $kbs);
        $this->view->assign('rec_kbs', $recKbs);
        $this->view->assign('title', $kbs['title']);
        $this->view->assign('category', $category);
        return $this->view->fetch();
    }

    public function icon()
    {
        $suffix = $this->request->param("suffix");
        header('Content-type: image/svg+xml');
        $suffix = $suffix ?: "FILE";
        echo $this->General->buildSuffixImage($suffix);
        exit;
    }
}
